package com.zdcp.core.web.controller;

import java.beans.PropertyEditorSupport;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.zdcp.core.bean.TableInfo;
import com.zdcp.core.constant.Constants;
import com.zdcp.util.DateUtils;
import com.zdcp.util.ServletUtils;
import com.zdcp.util.StringUtils;

/**
 * web层通用数据处理
 * @author yweijian
 * @date 2019年8月23日
 * @version 1.0
 */
public class BaseController {
	protected final Logger logger = LoggerFactory.getLogger(BaseController.class);
	
	private static int DEFAULT_PAGE_NUM  = 1;
	
	private static int DEFAULT_PAGE_SIZE  = 15;
	
	@SuppressWarnings("rawtypes")
	protected PageQuery query;

	/**
	 * 将前台传递过来的日期格式的字符串，自动转化为Date类型
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		// Date 类型转换
		binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				setValue(DateUtils.parseDate(text));
			}
		});
	}

	/**
	 * 获取request
	 */
	public HttpServletRequest getRequest() {
		return ServletUtils.getRequest();
	}

	/**
	 * 获取response
	 */
	public HttpServletResponse getResponse() {
		return ServletUtils.getResponse();
	}

	/**
	 * 获取session
	 */
	public HttpSession getSession() {
		return getRequest().getSession();
	}
	
	/**
	 * 初始化pageQuery
	 * @param entity
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	protected void initPageQuery(Object entity){
		PageQuery query = new PageQuery();
		query.setPageNumber(ServletUtils.getParameterToInt(Constants.PAGE_NUM, DEFAULT_PAGE_NUM));
		query.setPageSize(ServletUtils.getParameterToInt(Constants.PAGE_SIZE, DEFAULT_PAGE_SIZE));
		if(StringUtils.isNotEmpty(StringUtils.convertToUnderline(ServletUtils.getParameter(Constants.ORDER_BY_COLUMN)))){
			query.setOrderBy(StringUtils.convertToUnderline(ServletUtils.getParameter(Constants.ORDER_BY_COLUMN)) + " " + ServletUtils.getParameter(Constants.IS_ASC));
		}
		query.setParas(entity);
		this.setQuery(query);
	}

	/**
	 * 分页数据表格
	 */
	protected TableInfo getDataTable(PageQuery<?> query) {
		TableInfo tableDataInfo = new TableInfo();
		tableDataInfo.setCode(0);
		tableDataInfo.setRows(query.getList());
		tableDataInfo.setTotal(query.getTotalRow());
		return tableDataInfo;
	}

	/**
	 * 页面跳转
	 */
	public String redirect(String url) {
		return StringUtils.format("redirect:{}", url);
	}

	@SuppressWarnings("rawtypes")
	public PageQuery getQuery() {
		return query;
	}

	@SuppressWarnings("rawtypes")
	public void setQuery(PageQuery query) {
		this.query = query;
	}
}
